import { defineStore } from 'pinia'
import axios from '@/utils/axios'

export const useBookStore = defineStore('book', {
  state: () => ({
    books: [],
    categories: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchBooks() {
      this.loading = true
      try {
        const response = await axios.get('/api/books')
        this.books = response.data
        this.error = null
      } catch (error) {
        this.error = error.response?.data?.message || '获取书籍失败'
      } finally {
        this.loading = false
      }
    },
    
    async fetchCategories() {
      try {
        const response = await axios.get('/api/books/categories')
        this.categories = response.data
      } catch (error) {
        console.error('获取分类失败:', error)
      }
    },
    
    async uploadBook(formData) {
      try {
        const response = await axios.post('/api/books/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        return { success: true, data: response.data }
      } catch (error) {
        return { 
          success: false, 
          message: error.response?.data?.message || '上传失败' 
        }
      }
    },
    
    async searchBooks(keyword) {
      this.loading = true
      try {
        const response = await axios.get(`/api/books/search?keyword=${keyword}`)
        this.books = response.data
        this.error = null
      } catch (error) {
        this.error = error.response?.data?.message || '搜索失败'
      } finally {
        this.loading = false
      }
    },
    
    async deleteBook(id) {
      try {
        await axios.delete(`/api/books/${id}`)
        this.books = this.books.filter(book => book.id !== id)
        return { success: true }
      } catch (error) {
        return { 
          success: false, 
          message: error.response?.data?.message || '删除失败' 
        }
      }
    },
    
    async getBook(id) {
      try {
        const response = await axios.get(`/api/books/${id}`)
        return { success: true, data: response.data }
      } catch (error) {
        return { 
          success: false, 
          message: error.response?.data?.message || '获取书籍失败' 
        }
      }
    }
  }
})